package user

import (
	"gin/model"
	"gin/model/database"
	"gin/server"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Role struct {
}

// 角色列表
func (con Role) RoleList(c *gin.Context) {
	var roles []*model.Roles
	if err := database.DB.Table("role").Find(&roles).Error; err != nil {
		c.JSON(500, gin.H{
			"error": err,
		})
		return
	}

	c.HTML(http.StatusOK, "user/roleList.html", gin.H{
		"data": roles,
	})
}

func (con Role) RoleAdd(c *gin.Context) {
	m := &model.Roles{
		RoleName:    "",
		Description: "",
	}
	m.RoleName = c.PostForm("role_name")
	m.Description = c.PostForm("description")
	if m.RoleName == "" {
		c.JSON(200, gin.H{
			"code": 301,
			"msg":  "role_name参数不能为空",
			"data": nil,
		})
	}

	err := database.DB.Table("role").Save(&m).Error
	if err != nil {
		server.Success(c, "添加失败", err)
		return
	}
	server.Success(c, "添加成功", nil)
}

func (con Role) RoleDel(c *gin.Context) {
	m := &model.User{
		Id: 0,
	}
	m.Id, _ = strconv.Atoi(c.PostForm("id"))
	if m.Id == 0 {
		c.JSON(200, gin.H{
			"code": 301,
			"msg":  "删除ID不能为空",
			"data": nil,
		})
	}
	err := database.DB.Table("role").Delete(&m).Error
	if err != nil {
		server.Success(c, "删除失败", err)
		return
	}
	server.Success(c, "删除成功", nil)
}

// 修改
func (con Role) RoleUpd(c *gin.Context) {
	data := make(map[string]any)
	role_name := c.PostForm("role_name")
	description := c.PostForm("description")
	id := c.PostForm("id")
	if role_name != "" {
		data["role_name"] = role_name
	}
	if description != "" {
		data["description"] = description
	}
	if id == "" {
		server.Success(c, "更新ID不能为空", nil)
		return
	}
	//定义查询条件
	Role := &model.Roles{
		Id: 0,
	}
	Role.Id, _ = strconv.Atoi(id)
	//批量修改
	err := database.DB.Model(&Role).Updates(data).Error
	if err != nil {
		server.Success(c, "更新失败", err)
		return
	}
	server.Success(c, "更新成功", nil)
}
